﻿package 
{
	import flash.display.MovieClip;
	import flash.events.Event;
	import fl.motion.Color;
	import flash.globalization.Collator;
	import flash.display.Sprite;
	import flash.display.DisplayObject;
	import flash.geom.ColorTransform;
	
	public class Fader extends MovieClip 
	{
		private var faderWait:int;
		private var fadeSpeed:Number;
		public var PlayingFader:Boolean;
		public var CompletedTransition:Boolean;
		
		
		public function Fader() 
		{
			init();
			addEventListener(Event.ENTER_FRAME, EnterFrame);
			addEventListener(Event.REMOVED, Unload);
		}
		
		private function init():void
		{
			faderWait = 0;
			PlayingFader = false;
			
			setColor(Number("0x000000"));
			CompletedTransition = false;
			fadeSpeed = .2;
		}
		
		private function Unload(event:Event):void
		{
			if (event.target.name == this.name)
			{
				removeEventListener(Event.ENTER_FRAME, EnterFrame);
			}
		}
		
		private function EnterFrame(event:Event):void
		{
			if (PlayingFader)
			{
				if (this.alpha < 1)
				{
					this.alpha += fadeSpeed;
					if (this.alpha > 1)
					{
						this.alpha = 1;
					}
				}
				else if (this.alpha == 1)
				{
					CompletedTransition = true;
					if (faderWait > 0)
					{
						faderWait--;
					}
					else if (faderWait == 0)
					{
						PlayingFader = false;
					}
				}
			}
			else
			{
				if (this.alpha > 0)
				{
					this.alpha -= fadeSpeed;
					if (this.alpha < 0)
					{
						CompletedTransition = false;
						this.alpha = 0;
					}
				}
			}
		}
		
		private function setColor(color:Number)
		{
			var myColorTransform:ColorTransform = new ColorTransform();
			myColorTransform.color = color;
			this.transform.colorTransform = myColorTransform;
		}
		
		public function PlayFader(waitTime:int, color:Number, speed:Number):void
		{
			fadeSpeed = speed;
			setColor(color);
			this.alpha = 0;
			PlayingFader = true;
			faderWait = waitTime;
		}
	}
}